<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>serviceWorker</title>
  </head>
  <body>
    <p id="register"></p>
    <p id="kind"></p>
    <p id="states"></p>

    <script>
      function logState(state) {
        let liElement = document.createElement("li");
        liElement.textContent = state;
        document.querySelector("#states").appendChild(liElement);
      }

      if ("serviceWorker" in navigator) {
        navigator.serviceWorker
          .register("sw.js", { scope: "/" })
          .then(function (registration) {
            document.querySelector("#register").textContent = "succeeded";

            let serviceWorker;
            if (registration.installing) {
              serviceWorker = registration.installing;
              document.querySelector("#kind").textContent = "installing";
            } else if (registration.waiting) {
              serviceWorker = registration.waiting;
              document.querySelector("#kind").textContent = "waiting";
            } else if (registration.active) {
              serviceWorker = registration.active;
              document.querySelector("#kind").textContent = "active";
            }

            if (serviceWorker) {
              logState(serviceWorker.state);
              serviceWorker.addEventListener("statechange", function (e) {
                logState(e.target.state);
              });
            }
          })
          .catch(function (error) {
            document.querySelector("#register").textContent = "failed: " + error;
          });
      }
    </script>
  </body>
</html>
